package com.leejxx.backend.config;

import com.leejxx.blog.service.UserService;
import com.leejxx.common.pojo.Permission;
import com.leejxx.common.pojo.Role;
import com.leejxx.common.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @Author LeeJx
 * @ClassName SecurityUserDetailsService
 * @Description TODO
 * @date 2021/1/9 19:23
 * @Version 1.0
 */
@Service
@Slf4j
public class SecurityUserDetailsService implements UserDetailsService {

    @DubboReference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 模拟从数据库读取用户信息
//        User user = userDb.get(username);
        User user = userService.findByUsername(username);
        if(null == user){
            throw new UsernameNotFoundException("用户不存在");
        }

        String userName = user.getUsername();
        String password = user.getPassword();
        // 获取用户角色及权限
        Collection<GrantedAuthority> authList = new ArrayList<>();
        for(Role role:user.getRoles()){
            // 角色关键词
            authList.add(new SimpleGrantedAuthority(role.getKeyword()));
            for (Permission permission:role.getPermissions()){
                // 权限关键词
                authList.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        log.info("[获取用户认证权限权信息]userName:{},authorities:{}", userName, authList);
        return new org.springframework.security.core.userdetails.User(userName,password,authList);
    }
}
